define('common:widget/ui/ai/sider/sider', function(require, exports, module) {

  /**
   * @file AI工具Sider
   * @author yuyanyan01
   */
  
  var san = require('common:widget/ui/ai/san');
  var $ = require('common:widget/ui/base/base');
  var ButtonGroup = require('common:widget/ui/ai/buttonGroup/buttonGroup');
  var ButtonNew = require('common:widget/ui/ai/buttonNew/buttonNew');
  var TextArea = require('common:widget/ui/ai/textArea/textArea');
  var LevelSlider = require('common:widget/ui/ai/levelSlider/levelSlider');
  var DetailText = require('common:widget/ui/ai/detailText/detailText');
  var SendToast = require('common:widget/ui/ai/toast/toast');
  var lib = require('common:widget/ui/utils/lib');
  // 创建生成的任务id请求
  var createXhr = null;
  // 根据任务id请求生成的图片列表
  var queryXhr = null;
  var sideTips = {
      'replace': '第1步：涂抹要替换区域',
      'expand': '请选择拓展比例',
      'brush': '请涂抹选择你要替换的区域',
      'input': '第2步：描述修改内容',
      'reborn': '重绘程度',
      'similar': 'AI作图相似度',
      'remove': '请先涂抹你要消除的区域',
      'watermark': '涂抹去水印'
  };
  var detailTips = {
      'reborn': 'AI重绘利用AI算法对图片中模糊的细节进行重新塑造，可为您的草图、草稿生成更多有创意的细节',
      'similar': '相似图利用AI算法根据一张特定的图像，生成一系列与之相关或风格相似的图像'
  };
  var surveyController = require('common:widget/ui/ai/survey/controller');
  var PAGE = require('common:widget/ui/ai/survey/constant');
  
  return san.defineComponent({
      template: ''
          +   '<div class="ai-sider-container">'
          +       '<div class="ai-sider-top">'
          +           '<m-buttonGroup class="ai-sider-item"'
          +               'title="选择编辑方式"'
          +               'list="{{btnList}}"'
          +               'disabled="{{editDisabled}}"'
          +               'select-index="{{selectIndex}}"'
          +               'on-select="getSelectTool"/>'
          +       '</div>'
          +       '<div class="ai-sider-middle {{errorTip? \'ai-sider-tips-error\' : \'\'}} '
          +           '{{shakeAnime ? \'error-shake-anime\' : \'\'}} '
          +           '{{editDisabled ? \'edit-disabled\' : \'\'}}" '
          +           's-if="currentStatus !== editStatus.DEFAULT">'
          +           '<div class="expand-container"'
          +               's-if="selectType === toolTypeMap[toolType.EXPAND] && extRatio && extRatio.length"'
          +           '>'
          +               '<div class="ai-tool-title ai-tip-text">{{tipText}}</div>'
          +           '<m-buttonGroup '
          +               's-if="selectType === toolTypeMap[toolType.EXPAND] && extRatio && extRatio.length"'
          +               'class="ai-sider-item expand-ratio-item"'
          +               'need-click-cancel="{{true}}"'
          +               'list="{{extRatio}}"'
          +               'select-index="{=selectRatioIndex=}"'
          +               'disabled="{{editDisabled}}"'
          +               'col-num="{{3}}"'
          +               'width="112"'
          +               'height="40"'
          +               'on-select="getSelectRatio"/>'
          +           '</div>'
          +           '<m-buttonGroup '
          +               's-if="selectType === toolTypeMap[toolType.EXPAND] && extMulti && extMulti.length"'
          +               'class="ai-sider-item"'
          +               'need-click-cancel="{{true}}"'
          +               'title="拓展倍数"'
          +               'list="{{extMulti}}"'
          +               'select-index="{=selectMultiIndex=}"'
          +               'disabled="{{editDisabled}}"'
          +               'col-num="{{3}}"'
          +               'width="112"'
          +               'height="40"'
          +               'on-select="getSelectMulti"/>'
          +           '<m-level-slider '
          +               's-if="selectType === toolTypeMap[toolType.REBORN]"'
          +               'disabled="{{editDisabled}}"'
          +               'direction-text="{{directionText}}"'
          +               'show-label="{{true}}}"'
          +               'tip-text="{{tipText}}"'
          +               'default-step="{{rebornDefault}}"'
          +               'current-step-index="{{rebornDefault - 1}}"'
          +               'on-step-hover="handleStepHover"'
          +               'on-change="handleChangeLevel"/>'
          +           '<m-level-slider '
          +               's-else-if="selectType === toolTypeMap[toolType.SIMILAR]"'
          +               'disabled="{{editDisabled}}"'
          +               'direction-text="{{directionText}}"'
          +               'show-label="{{false}}}"'
          +               'tip-text="{{tipText}}"'
          +               'default-step="{{similarDefault}}"'
          +               'current-step-index="{{similarDefault - 1}}"'
          +               'on-step-hover="handleStepHover"'
          +               'on-change="handleChangeLevel"/>'
          +           '<m-level-slider '
          +               's-else-if="showBrush"'
          +               's-ref="brushSizeSlider"'
          +               'show-label="{{false}}}"'
          +               'show-step="{{false}}}"'
          +               'disabled="{{editDisabled}}"'
          +               'tip-text="{{tipText}}"'
          +               'is-ai-tip="{{brushError}}"'
          +               'title="{{brushSliderTitle}}"'
          +               'default-value="{{defaultBrushSize}}"'
          +               'min="{{brushMinSize}}"'
          +               'max="{{brushMaxSize}}"'
          +               'on-slider-mousedown="handleBrushMouseDown"'
          +               'on-slider-mouseup="handleBrushMouseUp"'
          +               'on-slider-mousemove="handleBrushMousemove"'
          +               'on-change="handleChangeBrushSize"/>'
          +           '<m-text-area '
          +               's-if="selectType === toolTypeMap[toolType.REPLACE]"'
          +               'list="{{promptList}}"'
          +               'disabled="{{editDisabled}}"'
          +               'is-ai-tip="{{inputError}}"'
          +               'tip-text="{{tipText}}"'
          +               'title="第2步：描述修改内容"'
          +               'content="{{prompts}}"'
          +               'on-focus="handleFocus"'
          +               'on-input="getInput"'
          +               'on-clear="handleClearTextArea"'
          +               'on-select="handleSelectPrompt"/>'
          +       '</div>'
          +       '<div class="ai-sider-bottom">'
          +           '<m-detail-text '
          +               's-if="(selectType === toolTypeMap[toolType.SIMILAR] '
          +                     '|| selectType === toolTypeMap[toolType.REBORN])'
          +                     '&& (currentStatus === \'edit\''
          +                           '|| currentStatus === \'fail\''
          +                           '|| currentStatus === \'loading\' )"'
          +                   'disabled="{{editDisabled}}"'
          +               'detail-text="{{detailText}}"/>'
          +           '<m-button s-if="currentStatus === \'loading\'"'
          +               'size="lg"'
          +               'class="cancel-btn"'
          +               'on-click="handleCancleGenerate">'
          +               '取消生成'
          +           '</m-button>'
          +           '<m-button '
          +               's-if="currentStatus !== \'loading\'"'
          +               'size="lg"'
          +               'class="generate-btn {{generateBtnDisabled ? \'generate-btn-disabled\' : \'\'}}"'
          +               'disabled="{{generateBtnDisabled}}"'
          +               'on-click="handleClickGenerate">'
          +               '<span>{{currentStatus === "loading" ? "正在生成" : "立即生成"}}</span>'
          +               '<div class="mask"></div>'
          +            '</m-button>'
          +       '</div>'
          +   '</div>',
      components: {
          'm-buttonGroup': ButtonGroup,
          'm-button': ButtonNew,
          'm-text-area': TextArea,
          'm-level-slider': LevelSlider,
          'm-detail-text': DetailText,
      },
  
      startTime: 0,
      endTime: 0,
      // 画质修复的点击次数
      clickRepairCount: 0,
      lastGenerateImg: [],
  
      // 创作的次数
      createCount: 0,
      timer: 0,
      dragging: false,
  
      initData: function () {
          return {
              originImg: {},
              canvasImage: {},
              query: '',
              toolType: {},
              toolTypeMap: {},
              editStatus: {},
              selectType: '-1',
              currentStatus: '',
              btnList: [],
              extRatio: [],
              extMulti: [],
              similarDefault: 5,
              rebornDefault: 5,
  
              currentRatio: '',
              currentMulti: '',
              currentCreatLevel: 0,
              selectRatioIndex: -1,
              selectMultiIndex: -1,
  
              prompts: '',
  
              promptList: null,
              selectIndex: -1,
              paintImage: null,
              clickManual: false,
  
              clickCancel: false,
              // 点击预览的图片index 0 表示点击原图
              previewIndex: -1,
              // 缩图信息
              thumbImg: {},
              tipText: '',
              errorTip: false,
              shakeAnime: false,
              detailText: '',
              // 是否第一次进入弹层
              firstAttach: false,
              directionText: {
                  left: '更接近原图',
                  right: '更有创造力'
              },
              brushSliderTitle: '画笔大小',
              brushMinSize: 5,
              brushMaxSize: 100,
              brushCurrentSize: 50,
              defaultBrushSize: 50,
              inputError: false,
              brushError: false,
          };
      },
  
      attached: function () {
          var _this = this;
          // 进入页面默认触发一次点击
          var selectType = this.data.get('selectType');
          this.data.set('firstAttach', true);
          // ai重绘 生成相似图 第一次进入页面触发。
          this.handleClickTool(selectType, false);
          // 埋点记录 当前的点击的type 和之前的功能type
          this.watch('selectType', function (val, oldValue) {
              // 当被重置时 selectType 被设置为 -1 其他类型的type点击事件派发在 handleClickTool
              if (+val === -1) {
                  this.fire('select-type', val);
              }
              var defaultSize = this.data.get('defaultBrushSize');
              if (this.ref('brushSizeSlider')) {
                  this.ref('brushSizeSlider').reset();
              }
              this.changeBrushCurrentSize(defaultSize, true);
              this.nextTick(function () {
                  _this.sendLog('show', 'edit', {
                      function: val
                  });
              });
          });
  
          var btnList = this.data.get('btnList');
          var index = btnList.findIndex(function (item) {
              return item.type === selectType;
          });
          this.setCurrentEditGuid(index, selectType);
  
          var toolTypeMap = this.data.get('toolTypeMap');
          var toolType = this.data.get('toolType');
  
  
          this.watch('currentStatus', function (val) {
              var selectType = this.data.get('selectType');
              // 当前是编辑态 且当前被选中的工具类型是 AI去水印 且点击了手动去水印时 这时候需要吧AI去水印高亮
              if ((selectType === toolTypeMap[toolType.WATERMARK]
                  || selectType === toolTypeMap[toolType.MANUAL])
                  && val === 'edit' && this.data.get('clickManual')) {
                  this.data.set('selectIndex', 0);
                  this.data.set('tipText', sideTips.watermark);
              }
              else if (val === 'default') {
                  this.data.set('selectIndex', -1);
                  // 重置时 创作次数为0
                  this.createCount = 0;
                  this.clickRepairCount = 0;
                  this.data.set('previewIndex', -1);
              }
              else if (val === 'complete') {
                  this.data.set('previewIndex', 1);
                  // 完成一次 如果是画质修复完成 则次数加1
                  if (this.data.get('selectType') === toolTypeMap[toolType.REPAIR]) {
                      this.clickRepairCount++;
                  }
                  else if (this.data.get('selectType') === toolTypeMap[toolType.REPLACE]) {
                      this.data.set('prompts', '');
                  }
                  // 已经创作过 则次数加1 否则认为是首次创作
                  this.createCount++;
  
                  surveyController.setData('currentFunction', this.data.get('selectType'));
                  var displayParams = surveyController.displayParams;
                  var count = displayParams.count;
                  var functionType = displayParams.functionType || [];
                  var page = displayParams.page;
                  if (page !== PAGE.EDIT) {
                      return;
                  }
                  if (count > 0 && this.createCount === count) {
                      surveyController.show(3);
                  }
                  else if (functionType.includes(this.data.get('selectType'))) {
                      surveyController.show(3);
                  }
                  if (this.data.get('selectType') === toolTypeMap[toolType.WATERMARK]) {
                      SendToast({
                          message: '已为您去除水印，不满意可手动去除或重置'
                      });
                      this.fire('enter-manual-water-mark', {resType: 0, sendlog: false});
                  }
              }
              this.fire('change-create-count', this.createCount);
          });
  
          this.watch('paintImage', function (val) {
              if (val) {
                  // 请求在这里发出
                  this.generateImg(val);
              }
          });
  
          this.watch('previewIndex', function (val) {
              // 如果是首次创作过 且 点击预览了原图 则吧创作次数设置为0
              // 首次创作过 点击非原图 则把 this.createCount 设置为1
              // 非首次创作 则直接返回创作的次数
              if (val === 0 && this.createCount === 1) {
                  this.createCount = 0;
              }
              else {
                  this.createCount = this.createCount > 1 ? this.createCount : 1;
              }
          });
  
          this.watch('selectRatioIndex', function (val, old) {
              if (old.oldValue === -1 && val !== -1) {
                  this.data.set('errorTip', false);
              }
          });
      },
  
      computed: {
          editDisabled() {
              return this.data.get('currentStatus') === 'loading';
          },
          selectIndex() {
              var _this = this;
              var selectType = this.data.get('selectType');
              var toolTypeMap = this.data.get('toolTypeMap');
              var toolType = this.data.get('toolType');
              var index = this.data.get('btnList').findIndex(function (item) {
                  return item.type === selectType;
              });
              // 如果是手动去水印 默认AI去水印是选中态
              if (selectType === toolTypeMap[toolType.MANUAL]) {
                  index = 0;
              }
              return index;
          },
  
          generateBtnDisabled() {
              // 可点击的时机 失败状态 或者 编辑状态 且
              // 局部替换 则必须要prompts 和当前画布已经涂抹了
              // 涂抹消除 当前画布已经涂抹了
              // 或者 画面延展 currentRatio | currentMulti 任意一个有值
              // 或者手动去水印 且进行了涂抹操作
              // 或者 图片再生
              // 或者 生成相似图
              // 如果AI去水印 或者画质拓展 时 点击取消生成 这时候 生成按钮可用
  
              var canUse = false;
              var currentStatus = this.data.get('currentStatus');
              var selectType = this.data.get('selectType');
              var selectRatioIndex = this.data.get('selectRatioIndex');
              var selectMultiIndex = this.data.get('selectMultiIndex');
              var hasBrush = this.data.get('hasBrush');
              var prompts = this.data.get('prompts');
              var toolTypeMap = this.data.get('toolTypeMap');
              var toolType = this.data.get('toolType');
  
              if (currentStatus === 'edit') {
                  if ((selectType === toolTypeMap[toolType.EXPAND] || selectMultiIndex !== -1)
                      || selectType === toolTypeMap[toolType.REPLACE]
                      || selectType === toolTypeMap[toolType.REMOVE]
                      || selectType === toolTypeMap[toolType.MANUAL]
                      || this.data.get('clickCancel') && (
                          selectType === toolTypeMap[toolType.WATERMARK]
                              || selectType === toolTypeMap[toolType.REPAIR]
                      )
                      || (selectType === toolTypeMap[toolType.SIMILAR] || selectType === toolTypeMap[toolType.REBORN])
                      && !this.data.get('firstAttach')
                  ) {
                      canUse = true;
                  }
              }
              else if (currentStatus === 'fail' || currentStatus === 'complete') {
                  canUse = true;
              }
              return !canUse;
          },
  
          canReplace() {
              return this.data.get('hasBrush') && this.data.get('prompts');
          },
          canRemove() {
              return this.data.get('hasBrush');
          },
          showBrush: function () {
              var selectType = this.data.get('selectType');
              var toolTypeMap = this.data.get('toolTypeMap');
              var toolType = this.data.get('toolType');
              switch (selectType) {
                  case toolTypeMap[toolType.REPLACE]:
                  case toolTypeMap[toolType.REMOVE]:
                  case toolTypeMap[toolType.MANUAL]:
                      return true;
                  default:
                      return false;
              }
          }
      },
  
      clearValue: function () {
          this.data.set('prompts', '');
          this.data.set('currentRatio', '');
          this.data.set('currentCreatLevel', 0);
          this.data.set('currentMulti', '');
          this.data.set('selectRatioIndex', -1);
          this.data.set('selectMultiIndex', -1);
      },
  
      handleClickTool: function (type, sendLog) {
          this.data.set('errorTip', false);
          var toolTypeMap = this.data.get('toolTypeMap');
          var toolType = this.data.get('toolType');
          var tipText = '';
          var detailText = '';
          if (type === toolTypeMap[toolType.REPLACE]
              || type === toolTypeMap[toolType.REMOVE]
              || type === toolTypeMap[toolType.MANUAL]) {
              if (type === toolTypeMap[toolType.REPLACE]) {
                  tipText = sideTips.replace;
              }
              else if (type === toolTypeMap[toolType.MANUAL]) {
                  tipText = sideTips.watermark;
              }
              else {
                  tipText = sideTips.remove;
              }
              this.fire('show-replace-guide', true);
          }
          else if (type === toolTypeMap[toolType.WATERMARK]) {
              tipText = sideTips.watermark;
          }
          else {
              // 如果是type=8,涂抹清除功能也复用replace-guide
              this.fire('show-replace-guide', false);
          }
          if (type === toolTypeMap[toolType.EXPAND]) {
              tipText = sideTips.expand;
          }
          if (type === toolTypeMap[toolType.REBORN]) {
              tipText = sideTips.reborn;
              detailText = detailTips.reborn;
          }
          if (type === toolTypeMap[toolType.SIMILAR]) {
              tipText = sideTips.similar;
              detailText = detailTips.similar;
          }
          this.data.set('tipText', tipText);
          this.data.set('detailText', detailText);
  
          // 避免首次进入的时候log发送重复
          if (sendLog) {
              // 手动去水印模式下，点击ai去水印 需要打点击的log，但是不需要进行自动去水印操作
              var tempFunction = this.data.get('clickManual') && type === toolTypeMap[toolType.WATERMARK] ? toolTypeMap[toolType.MANUAL] : type;
              this.sendLog('click', 'function', {
                  before_function: this.data.get('selectType'),
                  function: tempFunction
              });
          }
  
          // 手动去水印模式下点击AI去水印 不进行后续操作 但是需要打点击的点
          if (type === toolTypeMap[toolType.WATERMARK] && this.data.get('clickManual')) {
              return;
          }
          // 切换别的工具时需要吧手动去水印模式消除
          this.data.set('clickManual', false);
          this.fire('select-type', type);
  
          if (type === toolTypeMap[toolType.REPAIR] && this.clickRepairCount >= 1) {
              SendToast({
                  message: '图片已经很清晰了，换张图片再试试~'
              });
              this.fire('generate-img-list', {
                  list: this.lastGenerateImg,
                  needUnshift: false,
                  noRender: true,
                  generatedSelectType: type
              });
              this.fire('change-edit-status', 'complete');
              return;
          }
  
          // 如果取消生成 当前点击的工具等于之前的 且当前点击的是画面延展或者局部替换ai重绘，ai相似图时 不进行后续的操作
          if (this.data.get('clickCancel') && this.data.get('selectType') === type &&
              (type === toolTypeMap[toolType.EXPAND]
                  || type === toolTypeMap[toolType.REPLACE]
                  || type === toolTypeMap[toolType.REBORN]
                  || type === toolTypeMap[toolType.SIMILAR])) {
              return;
          }
  
  
          this.fire('change-click-manual', false);
          // 切换工具吧之前的选择清空
          this.clearValue();
          // 不是手动去水印时 点击AI去水印和画质修复 直接进入loading状态 否则进入编辑状态
          if ((!this.data.get('clickManual')
              && (type === toolTypeMap[toolType.WATERMARK] || type === toolTypeMap[toolType.REPAIR]))
              || (this.data.get('firstAttach')
              && (type === toolTypeMap[toolType.REBORN] || type === toolTypeMap[toolType.SIMILAR]))) {
              this.data.set('firstAttach', false);
              this.fire('change-edit-status', 'loading');
              var _this = this;
              this.nextTick(function () {
                  _this.fire('click-generate', true);
              });
          }
          else {
              this.data.set('firstAttach', false);
              this.fire('change-edit-status', 'edit');
          }
  
          if (type === toolTypeMap[toolType.REBORN]) {
              this.data.set('currentCreatLevel', this.data.get('rebornDefault'));
          }
          if (type === toolTypeMap[toolType.SIMILAR]) {
              this.data.set('currentCreatLevel', this.data.get('similarDefault'));
          }
      },
  
      setCurrentEditGuid: function (index, type) {
          var btnList = this.data.get('btnList');
          this.fire('edit-guide', {
              tool: btnList[index],
              type
          });
      },
  
      getSelectTool: function (data) {
          var index = data.index;
          var item = data.item || {};
          var type = item.type;
          this.handleClickTool(type, true);
          this.setCurrentEditGuid(index, type);
      },
  
      getSelectRatio: function (data) {
          var item = data.item;
          var originImg = this.data.get('originImg');
          // var value = item.value || (originImg.width + ':' + originImg.height);
          var value = item.value;
          this.data.set('currentRatio', value);
          this.fire('current-ratio', value);
          this.sendLog('click', 'expand_ratio', {
              ratio: item.value
          });
      },
  
      getSelectCreateLevel: function (value) {
          this.fire('current-create-level', value);
      },
  
      getSelectMulti: function (data) {
          var item = data.item;
          var value = item.value || 1;
          this.data.set('currentMulti', value);
          this.fire('current-multi', value);
          this.sendLog('click', 'expand_multiple', {
              multiple: item.value
          });
      },
  
      handleChangeLevel: function (value) {
          this.sendLog('click', 'adjust', {
              before_pxiel: this.data.get('currentCreatLevel'),
              after_pixel: value
          });
          this.data.set('currentCreatLevel', value);
      },
  
      sendGenerateLog: function (ext) {
          var currentRatio = this.data.get('currentRatio');
          var currentCreatLevel = this.data.get('currentCreatLevel');
          var currentMulti = this.data.get('currentMulti');
          var prompts = this.data.get('prompts');
          var selectType = this.data.get('selectType');
          var toolTypeMap = this.data.get('toolTypeMap');
          var toolType = this.data.get('toolType');
          var extraLog = {};
          if (selectType === toolTypeMap[toolType.EXPAND]) {
              extraLog = {
                  multiple: currentMulti,
                  ratio: currentRatio
              };
          }
          if (selectType === toolTypeMap[toolType.REPLACE]) {
              extraLog = {
                  content: prompts
              };
          }
          if (selectType === toolTypeMap[toolType.REBORN] || selectType === toolTypeMap[toolType.SIMILAR]) {
              extraLog = {
                  slider_pos: '' + currentCreatLevel
              };
          }
          var param = ext ? ext : {};
  
          this.sendLog('click', 'generate', $.extend({}, param, extraLog));
      },
  
      getImgList: function (imgParams, taskType) {
          if (this.data.get('clickCancel')) {
              return;
          }
          var taskId = this.taskId;
  
          // 从历史记录中还原/撤销图片时，用历史中的参数
          var params = imgParams || {
              taskId,
              query: this.data.get('query')
          };
          queryXhr = this._ajax('/aigc/pcquery', 'get', params);
          var _this = this;
          queryXhr.then(function (response) {
              if (!response.isGenerate) {
                  _this.fire('progress', response.progress);
                  setTimeout(function () {
                      _this.getImgList(this.taskId);
                  }, 1000);
              }
              else {
                  _this.endTime = new Date().getTime();
                  var generateStatus = false;
                  var editStatus = '';
                  if (Array.isArray(response.picArr)) {
                      _this.fire('generate-img-list', {
                          list: response.picArr,
                          needUnshift: true,
                          generatedSelectType: _this.data.get('selectType'),
                          taskType
                      });
  
                      // 将当前请求参数进行上报，用于存储历史
                      _this.fire('save-history', {
                          params,
                          taskType
                      });
                      _this.fire('change-edit-status', 'complete');
                      editStatus = 'complete';
                      // 点击手动去水印 需要等生成成功之后再把手动去水印的点击状态设置为false
                      // 否则当手动去水印 点击取消生成时 会缺少画笔状态
                      _this.fire('change-click-manual', false);
                      generateStatus = true;
                      _this.lastGenerateImg = response.picArr;
                  }
                  else {
                      _this.fire('generate-img-list', {
                          list: null,
                          needUnshift: false,
                          generatedSelectType: _this.data.get('selectType')
                      });
                      SendToast({
                          message: response.message || '服务异常，请稍后重试~'
                      });
                      _this.fire('change-edit-status', 'fail');
                      editStatus = 'fail';
                      generateStatus = false;
                  }
  
                  _this.sendLog('show', 'generate', {
                      taskId: _this.taskId,
                      generate_status: generateStatus,
                      image_cnt: Array.isArray(response.picArr) ? response.picArr.length : 0,
                      dura: _this.endTime - _this.startTime,
                      edit_status: editStatus
                  });
              }
          });
      },
  
      _ajax: function (url, type, params) {
          return $.ajax({
              url,
              type,
              data: params,
              error: function (err) {
                  SendToast({
                      message: '前方拥挤，请稍后重试'
                  });
              }
          });
      },
  
      // 请求后端接口生成图片
      generateImg: function (res) {
          this.data.set('clickCancel', false);
          var picInfo = this.data.get('canvasImage').src;
          var currentRatio = this.data.get('currentRatio');
          var currentCreatLevel = this.data.get('currentCreatLevel');
          var currentMulti = this.data.get('currentMulti');
          var originImg = this.data.get('originImg');
          var prompts = this.data.get('prompts');
          var picInfo2 = '';
          if (res) {
              picInfo = res.imageSrc;
              picInfo2 = res.maskSrc;
          }
          var type = this.data.get('selectType');
          var toolTypeMap = this.data.get('toolTypeMap');
          var toolType = this.data.get('toolType');
          this.fire('change-stage', type === toolTypeMap[toolType.WATERMARK]);
          this.fire('progress', 0);
  
          if (type === toolTypeMap[toolType.WATERMARK] && picInfo2) {
              type = toolTypeMap[toolType.MANUAL];
          }
          // picInfo 首次创作时 这个是缩图的base64 再次请求时 是你们返回的base64
          // picInfo2 是涂抹的黑白base64
          // original_url: 首次创作时 给原图的链接
          var params = {
              query: this.data.get('query'),
              picInfo,
              picInfo2,
              type,
              text: prompts,
              ext_ratio: currentRatio,
              expand_zoom: currentMulti,
              // createCount === 0 表示是首次用原图创作 需要给接口传originalurl，但是如果画布初始展现的是缩图 则不需要传origin_url
              original_url: this.createCount === 0 && originImg.isOrigin ? originImg.src : '',
              // 缩图地址
              thumb_url: this.data.get('thumbImg').src,
              // 用于session和后端存储的数据关联,分析当前用户在大图页面编辑之后 是否得到自己满意的结果，全链路分析
              clid: window.logid,
              // front_display（0:表示前端展示原图，1:表示前端展示缩略图，2:表示处理图）
              front_display: this.createCount > 0 ? 2 : originImg.isOrigin ? 0 : 1,
              create_level: currentCreatLevel,
          };
  
          this.startTime = new Date().getTime();
          var createStartTime = this.startTime;
  
          createXhr = this._ajax('/aigc/pccreate', 'post', params);
          var _this = this;
          createXhr.then(function (response) {
              var res = lib.parseResponse(response);
              var createEndTime = new Date().getTime();
              if (res.status) {
                  SendToast({
                      message: res.message || '服务异常，请稍后重试~'
                  });
                  // 生成失败时 不能设置完成 应该有个失败的状态管理
                  _this.fire('change-edit-status', 'fail');
              }
              else {
                  var taskId = res.pcEditTaskid;
                  if (taskId) {
                      _this.taskId = taskId;
                      _this.fire('task-id', taskId);
                      // loading展示progresss
                      _this.fire('change-stage', false);
                      _this.getImgList();
                  }
                  else {
                      // 识别到水印，直接返回图片结果，值为0；
                      // 水印过多，值为1；
                      // 未识别到水印 值为2
                      // 这两种情况下 直接帮用户点击手动去水印
                      var resType = res.resType;
                      // 手动去水印 进入编辑态
                      _this.fire('change-edit-status', 'eidt');
                      // 调起手动去水印，但是不单独打手动去水印的按钮的点
                      _this.fire('enter-manual-water-mark', {resType, sendlog: false});
                  }
              }
              var extra = {
                  generate_status: res.status === 0,
                  taskId: res.pcEditTaskid,
                  dura: createEndTime - createStartTime,
                  is_interact: 1
              };
              // 只有去水印功能带checkbox_status
              if (params.type === toolTypeMap[toolType.WATERMARK]) {
                  extra.checkbox_status = '' + (res.resType || 0);
              }
              _this.sendLog('show', 'create', extra);
          }).fail(function () {
              _this.fire('change-edit-status', 'fail');
          });
      },
  
      handleClickGenerate: function () {
          var selectRatioIndex = this.data.get('selectRatioIndex');
          var selectType = this.data.get('selectType');
          var toolTypeMap = this.data.get('toolTypeMap');
          var toolType = this.data.get('toolType');
          var hasBrush = this.data.get('hasBrush');
          var prompts = this.data.get('prompts');
          var text = '';
          if ((selectType === toolTypeMap[toolType.EXPAND] && selectRatioIndex === -1)
              || (selectType === toolTypeMap[toolType.REPLACE] && !this.data.get('canReplace'))
              || ((selectType === toolTypeMap[toolType.REMOVE] || selectType === toolTypeMap[toolType.MANUAL])
                  && !this.data.get('canRemove'))) {
              this.data.set('errorTip', true);
              this.data.set('inputError', !prompts);
              this.data.set('brushError', !hasBrush);
              this.shakeTip();
              text = sideTips.expand;
              if (selectType === toolTypeMap[toolType.REPLACE]) {
                  text = sideTips.replace;
              }
              else if (selectType === toolTypeMap[toolType.REMOVE] && !hasBrush) {
                  text = sideTips.remove;
              }
              else if (selectType === toolTypeMap[toolType.MANUAL]) {
                  text = sideTips.watermark;
              }
  
              this.data.set('tipText', text);
          }
          else {
              this.data.set('errorTip', false);
              this.fire('click-generate', true);
              this.fire('change-edit-status', 'loading');
          }
          this.sendGenerateLog(text ? {tips_word: text} : null);
      },
  
      handleCancleGenerate: function () {
          var currentRatio = this.data.get('currentRatio');
          var currentCreatLevel = this.data.get('currentCreatLevel');
          var currentMulti = this.data.get('currentMulti');
          var prompts = this.data.get('prompts');
          var selectType = this.data.get('selectType');
          var toolTypeMap = this.data.get('toolTypeMap');
          var toolType = this.data.get('toolType');
          var extra = {};
          if (selectType === toolTypeMap[toolType.EXPAND]) {
              extra = {
                  multiple: currentMulti,
                  ratio: currentRatio
              };
          }
          if (selectType === toolTypeMap[toolType.REPLACE]) {
              extra = {
                  content: prompts
              };
          }
          if (selectType === toolTypeMap[toolType.REBORN] || selectType === toolTypeMap[toolType.SIMILAR]) {
              extra = {
                  slider_pos: '' + currentCreatLevel
              };
          }
  
          this.data.set('clickCancel', true);
          this.sendLog('click', 'cancel', extra);
          createXhr && createXhr.abort();
          queryXhr && queryXhr.abort();
          this.fire('change-edit-status', 'edit');
      },
  
      handleClearTextArea: function () {
          this.sendLog('click', 'prompt_clear');
      },
      getInput: function (data) {
          this.data.set('prompts', data);
      },
  
      handleFocus: function () {
          this.sendLog('click', 'prompt_input');
      },
  
      handleSelectPrompt: function (data) {
          this.sendLog('click', 'prompt_rec', {
              content: data.item
          });
      },
  
      sendLog: function (type, value, extra) {
          var originImg = this.data.get('originImg');
          var query = this.data.get('query');
          var selectType = this.data.get('selectType');
          var currentStatus = this.data.get('currentStatus');
          var ext = $.extend({}, {
              image: originImg.src,
              query,
              function: selectType,
              edit_status: currentStatus
          }, extra);
  
          for (var key in extra) {
              if (extra.hasOwnProperty(key)) {
                  ext[key] = extra[key];
              }
          }
          this.dispatch('send-log', {
              type,
              value,
              ext
          });
      },
  
      shakeTip: function () {
          this.data.set('shakeAnime', true);
          var _this = this;
          setTimeout(function () {
              _this.data.set('shakeAnime', false);
          }, 450);
      },
  
      handleChangeBrushSize: function (value) {
          this.fire('show-replace-guide', false);
          this.changeBrushCurrentSize(value);
      },
  
      handleBrushMouseUp: function () {
          this.dragging = false;
          this.fire('brush-preview-change', {size: 0});
      },
  
      handleBrushMouseDown: function () {
          this.fire('show-replace-guide', false);
          this.dragging = true;
          var currentSize = this.data.get('brushCurrentSize');
          this.fire('brush-preview-change', {size: currentSize});
      },
  
      handleBrushMousemove: function (val) {
          clearTimeout(this.timer);
          this.changeBrushCurrentSize(val);
      },
  
      handleStepHover: function (val) {
          this.sendLog('hover', 'adjust', {
              before_pxiel: val,
              after_pixel: val
          });
      },
  
      changeBrushCurrentSize: function (val, init = false) {
          if (val !== this.data.get('brushCurrentSize')) {
              this.sendLog('click', 'adjust', {
                  before_pxiel: this.data.get('brushCurrentSize'),
                  after_pixel: val
              });
          }
          this.data.set('brushCurrentSize', val);
          this.fire('brush-preview-change', {size: val, init});
          this.fire('size-change', val);
          clearTimeout(this.timer);
          if (this.dragging || init) {
              return;
          }
          var _this = this;
          this.timer = setTimeout(function () {
              _this.fire('brush-preview-change', {size: 0});
          }, 200);
      }
  });
  

});
